﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using Ionic.Zip;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace PC.AzureMultiApp.Core.Helpers
{
    public static class FileHelper
    {
        public static bool Unzip(string zipFile, string targetFolder, bool doBackup)
        {
            bool result = false;
            string backupFile = string.Empty;

            Trace.WriteLine("Unzip" + zipFile, "Information");

            if (!File.Exists(zipFile))
                throw new ArgumentException("Zip file no exits");

            if (!Directory.Exists(targetFolder))
                throw new ArgumentException("Target Folder  no exits");

            try
            {
                if (doBackup && Directory.GetFiles(targetFolder).Any())
                    backupFile = DoBackup(targetFolder);

                using (ZipFile zip = new ZipFile(zipFile))
                {
                    zip.ExtractAll(targetFolder, ExtractExistingFileAction.OverwriteSilently);

                    if (File.Exists(backupFile))
                        File.Delete(backupFile);

                    result = true;
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message, "Error");

                if (doBackup)
                    RestoreBackup(backupFile, targetFolder);
            }

            return result;
        }

        private static string DoBackup(string targetFolder)
        {
            string backupFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            using (ZipFile zip = new ZipFile(backupFile))
            {
                zip.AddDirectory(targetFolder);
                zip.Save();
                Directory.Delete(targetFolder, true);

                if (!Directory.Exists(targetFolder))
                    Directory.CreateDirectory(targetFolder);
            }
            return backupFile;
        }

        private static void RestoreBackup(string backupFile, string targetFolder)
        {
            if (String.IsNullOrEmpty(backupFile) && File.Exists(backupFile))
            {
                using (ZipFile zip = new ZipFile(backupFile))
                {
                    zip.ExtractAll(targetFolder, ExtractExistingFileAction.OverwriteSilently);
                }
            }
        }

        public static string GetFilesFromStorage(string blobUrl)
        {

            if (String.IsNullOrEmpty(blobUrl))
                throw new ArgumentNullException("blobUrl");

            Trace.WriteLine("GetFilesFromStorage" + blobUrl, "Information");

            string localZipFile = string.Empty;

            try
            {
                CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("azuremultiappstorage");

                CloudBlobClient blobServiceClient = account.CreateCloudBlobClient();

                CloudBlob blob = blobServiceClient.GetBlobReference(blobUrl);

                if (blob != null)
                {
                    // Create temp directory
                    localZipFile = Path.GetTempFileName();
                    blob.DownloadToFile(localZipFile);
                }

            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message, "Error");
            }

            return localZipFile;
        }



        public static string GetBaseDirectory()
        {
            string appRoot = Path.Combine(Environment.GetEnvironmentVariable("RoleRoot") + @"\", @"approot" + @"\");
            return Path.Combine(appRoot, "DeploymentSite");
        }

    }
}
